package com.hs.auth.service.impl;

import com.hs.auth.service.LogService;
import com.hs.common.core.constant.Constants;
import com.hs.common.core.constant.SecurityConstants;
import com.hs.common.core.utils.StringUtils;
import com.hs.common.core.utils.ip.IpUtils;
import com.hs.system.api.feign.RemoteLogService;
import com.hs.system.api.entity.LoginInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 记录日志方法
 */
@Service
public class LogServiceImpl implements LogService {
    @Resource
    private RemoteLogService remoteLogService;

    @Value("${hs.log.enabled}")
    private boolean logEnabled;

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息内容
     * @return
     */
    public void recordLoginInfo(String username, String status, String message) {
        if (!logEnabled){
            return;
        }
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setUserName(username);
        loginInfo.setIpaddr(IpUtils.getIpAddr());
        loginInfo.setMsg(message);
        loginInfo.setAccessTime(LocalDateTime.now());
        // 日志状态
        if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
            loginInfo.setStatus(Constants.LOGIN_SUCCESS_STATUS);
        } else if (Constants.LOGIN_FAIL.equals(status)) {
            loginInfo.setStatus(Constants.LOGIN_FAIL_STATUS);
        }
        remoteLogService.saveLoginInfo(loginInfo, SecurityConstants.INNER);
    }
}
